package com.le.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

//下载文件
public class response01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realpath= this.getServletContext().getRealPath("/WEB-INF/classes/qq.png");

        String filename = realpath.substring(realpath.lastIndexOf("\\") + 1);

        resp.setHeader("Content-disposition","attachment;filename="+filename);
        //如果文件名是中文可以用下面的转换，不然会是乱码
        //URLEncoder.encode(filename,"utf-8")

        FileInputStream in = new FileInputStream(realpath);

        int len=0;
        byte[] buffer = new byte[1024];

        ServletOutputStream out = resp.getOutputStream();

        while ((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }

        out.close();
        in.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
